#!/usr/bin/env python

from sqlhandler import *
import conf

class DataHandler:
    def __init__(self):
        self.en = engine(conf.db_dev)
        self.boats = []
        self.boatId = 0
        self.init_colors()
        self.is_begin_game = False
        self.turn_id = 1

    def init_colors(self):
        self.colors = []
        delta = 256 / conf.max_boats
        for i in range(conf.max_boats):
            color = i * delta
            color = '#%03x' % color
            self.colors.append(color)

    def conflict(self, x, y):
        for boat in self.boats:
            if x == boat['x'] and y == boat['y']:
                return True
        return False

    def ask_begin(self):
        return {
            'is_begin_game' : self.is_begin_game,
            'turn_id' : self.turn_id
        }
    def begin_game(self):
        self.is_begin_game = True
        return {
            'is_begin_game' : self.is_begin_game,
            'turn_id' : self.turn_id
        }

    def get_next_pos(self, x, y):
        if x < conf.width:
            x += 1
        else:
            x = 0
            y = (y+1) % conf.height
        return x, y

    def get_init_data(self, name, x, y):
        if self.is_begin_game:
            return {'desc' : 'The game has began.'}
        if self.boatId < conf.max_boats:
            self.boatId += 1
            while self.conflict(x, y):
                print 'conflict %d %d' % (x, y)
                x, y = self.get_next_pos(x, y)
            item = {
                'name' : name,
                'x' : x,
                'y' : y,
                'Id' : self.boatId,
                'color' : self.colors[self.boatId],
                'btype' : 0,
                'desc' : 'welcome ' + name
            }
            if 0 == len(self.boats):
                item['youaremaster'] = True
            self.boats.append(item)
        else:
            item = {'Id' : -1}
        return item

    def get_map_size(self):
        item = {
            'width' : conf.width,
            'height' : conf.height
        }
        return item

    def get_boats_info(self):
        item = {'boats' : self.boats}
        return item
